package com.share.tool.m2d.drds;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ProcessSql {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("参数个数错误");
            return;
        }
        String sql = args[0];
        int index = sql.indexOf("INTO") + 4;
        int firstLIndex = sql.indexOf("(");
        int firstRindex = sql.indexOf(")");
        String tableName = sql.substring(index, firstLIndex).trim();

        //参数
        String fieldStr = sql.substring(sql.indexOf("("), sql.indexOf(")")).substring(1);
        String[] field = fieldStr.replace(" ", "").split(",");
        field = Arrays.copyOfRange(field, 1, field.length - 1);
//        fieldStr = StringUtils.join(field, ",");
        fieldStr = Arrays.stream(field).collect(Collectors.joining(","));


        int secondLIndex = sql.lastIndexOf("(");
        int secondRIndex = sql.lastIndexOf(")");
        String fieldValueStr = sql.substring(secondLIndex, secondRIndex).substring(1);
        String[] fieldValue = fieldValueStr.split(",");
        fieldValue = Arrays.copyOfRange(fieldValue, 1, fieldValue.length - 1);
//        fieldValueStr = StringUtils.join(fieldValue, ",");
        fieldValueStr = Arrays.stream(fieldValue).collect(Collectors.joining(","));

        List<String> list = new ArrayList<>();
        for (int i = 0; i < field.length; i++) {
            if (i != 0 && i != 2) {
                list.add(field[i]);
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append("INSERT INTO ").append(tableName).append(" ").append("(").append(fieldStr).append(") ").append("VALUES ").append("(").append(fieldValueStr).append(") ").append("ON DUPLICATE KEY UPDATE ");
        for (int i = 0; i < list.size(); i++) {
            if (i != list.size() - 1) {
                builder.append(list.get(i)).append(" = ").append("VALUES").append("(").append(list.get(i)).append(")").append(",");
            } else {
                builder.append(list.get(i)).append(" = ").append("VALUES").append("(").append(list.get(i)).append(")").append(";");
            }
        }

        System.out.println(builder.toString());
    }
}
